<?php
// +----------------------------------------------------------------------
// | XShop小程序商城
// +----------------------------------------------------------------------
// | Author: Peak Xin <xinyflove@gmail.com>
// +----------------------------------------------------------------------

namespace app\api\service;


use app\api\model\User as UserModel;
use app\lib\exception\OrderException;
use app\lib\exception\UserException;

/**
 * 发货微信模版消息管理
 * Class DeliveryMessage
 * @package app\api\service
 */
class DeliveryMessage extends WxMessage {
    
    const DELIVERY_MSG_ID = 'your wx template ID';// 小程序模板消息ID号

    /**
     * 发送发货模版消息
     * @param $order 订单数据
     * @param string $tplJumpPage 跳转页面
     * @return mixed
     * @throws OrderException
     */
    public function sendDeliveryMessage($order, $tplJumpPage = '')
    {
        if (!$order) {
            throw new OrderException();
        }
        $this->_tplID = self::DELIVERY_MSG_ID;
        $this->_formID = $order->prepay_id;
        $this->_page = $tplJumpPage;
        $this->__prepareMessageData($order);
        $this->_emphasisKeyWord='keyword2.DATA';
        return parent::_sendMessage($this->__getUserOpenID($order->user_id));
    }

    /**
     * 准备消息数据
     * @param $order 订单信息
     */
    private function __prepareMessageData($order)
    {
        $dt = new \DateTime();
        $data = [
            'keyword1' => [
                'value' => '顺风速运',// 快递公司
            ],
            'keyword2' => [
                'value' => $order->snap_name,// 订单快照名称
                'color' => '#27408B'
            ],
            'keyword3' => [
                'value' => $order->order_no// 订单号
            ],
            'keyword4' => [
                'value' => $dt->format("Y-m-d H:i")
            ]
        ];
        $this->_data = $data;
    }

    /**
     * 获取微信粉丝的openid
     * @param $uid
     * @return mixed
     * @throws UserException
     */
    private function __getUserOpenID($uid)
    {
        $user = UserModel::get($uid);
        if (!$user) {
            throw new UserException();
        }
        return $user->openid;
    }
}